package cn.seapon.talker.edit;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.seapon.talker.R;
import cn.seapon.talker.infocarrier.SharedItems;
import cn.seapon.talker.net.HttpRequest;

public class NickAvatarEditActivity extends Activity {

	private static final String TAG = "||__NickAvatarEditActivity__||";
	private EditText et_value;
	private Button save_btn;
	
	private String avatarname = "";
	private GridView gridview;

	private ImageView iv_avatar;
	private static ArrayList<HashMap<String,Object>> avatarsArrayList  =new ArrayList<HashMap<String,Object>>();
	private static final String EDIT_MAIL_URL = "http://1.lichtung.sinaapp.com/appserver/appservice.php?request_code=2006";
	private OnClickListener backlistener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			NickAvatarEditActivity.this.finish();
		}
	};
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Toast.makeText(NickAvatarEditActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
				Log.d(TAG, "修改成功");
				save_btn.setText("返回主页面");
				save_btn.setOnClickListener(backlistener);
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.save_btn:
				final String newvalue = et_value.getText().toString().trim();
				final String url = EDIT_MAIL_URL + "&new_nickname="
						+ URLEncoder.encode(newvalue) + "&userid="
						+ SharedItems.userInformation.getAccount()
						+"&new_avatar="+URLEncoder.encode(avatarname);
				Log.d(TAG, url);
				Thread thread = new Thread(){

					@Override
					public void run() {
						String retString = HttpRequest.doGetRequest(url);
						Message message = Message.obtain();
						if ("success".equals(retString)) {
							message.what = 1;
							if (!TextUtils.isEmpty(newvalue)) {
								SharedItems.userInformation.setNickname(newvalue);
							}
							if (!TextUtils.isEmpty(avatarname)) {
								SharedItems.userInformation.setAvatar(avatarname);
								
							}
							handler.sendMessage(message);
						}
					}
					
				};
				thread.start();
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_nick_avatar_edit);
		et_value = (EditText) findViewById(R.id.et_value);
		save_btn = (Button) findViewById(R.id.save_btn);

		gridview = (GridView) findViewById(R.id.gv_avatars);
		iv_avatar = (ImageView) findViewById(R.id.iv_avatar);
		
		initResource();
		
		SimpleAdapter adapter = new SimpleAdapter(this, avatarsArrayList,
				R.layout.avatar_item, new String[] { "id","id" ,"name"},
				new int[] { R.id.ItemImage,R.id.ItemId,R.id.ItemName});
		gridview.setAdapter(adapter);

		save_btn.setOnClickListener(listener);
		gridview.setOnItemClickListener(new ItemClickListener());
	}

	 class ItemClickListener implements OnItemClickListener {
	        /**
	         * 点击项时触发事件
	         * 
	         * @param parent  发生点击动作的AdapterView
	         * @param view 在AdapterView中被点击的视图(它是由adapter提供的一个视图)。
	         * @param position 视图在adapter中的位置。
	         * @param rowid 被点击元素的行id。
	         */
	        public void onItemClick(AdapterView<?> parent, View view, int position, long rowid) {
				TextView tv_name  = (TextView)view.findViewById(R.id.ItemName);
				String avatar_name = tv_name.getText().toString().trim();
				TextView tv_id  = (TextView)view.findViewById(R.id.ItemId);
				String avatar_id = tv_id.getText().toString().trim();
				//Toast.makeText(RegisterFinishActivity.this, "你点击的是："+resourceId+"   图片名字是:"+text, Toast.LENGTH_SHORT).show();
//				iv_avatar.setImageResource(resourceId);
				iv_avatar.setImageResource(Integer.valueOf(avatar_id));
				avatarname = avatar_name;
	        }
	    }

	/**
	 * 加载表情资源到程序中（反射 ）
	 */
	public static void initResource() {
		int count = 0;
		for (int i = 1; i <= 373; i++) {
			try {
				Field field = R.drawable.class.getDeclaredField("avatar_" + i);
				HashMap<String, Object> avatar = new HashMap<String, Object>();
				avatar.put("id", field.getInt(null));
				avatar.put("name", "avatar_" + count);
				count++;
				avatarsArrayList.add(avatar);
			} catch (NoSuchFieldException e) {
//				Log.d(TAG, "找不到资源");
//				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
}
